package com.yuan.util.system;

import com.yuan.util.string.ReuseStringBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 系统相关工具类
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/7/11 10:34
 * @UpdateDate 2018/7/11 10:34
 */
public class SystemUtil {

    /**
     * 执行系统命令行
     * @param command
     * @return
     */
    public static String execCommand(String command) {
        try {
            String osName = System.getProperty("os.name");
            if(osName != null) {
                Process exec = null;
                if(osName.contains("Windows")) {
                    exec = Runtime.getRuntime().exec(new String[]{"cmd", "/c", command});
                } else if (osName.contains("Linux")){
                    exec = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", command});
                } else {
                    throw new RuntimeException("未知的操作系统:" + osName);
                }
                InputStreamReader streamReader = new InputStreamReader(exec.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                StringBuilder stringBuilder = ReuseStringBuilder.getStringBuilder();
                String temp = null;
                while ((temp = reader.readLine()) != null) {
                    stringBuilder.append(temp).append("\n");
                }
                reader.close();
                return stringBuilder.toString();
            } else {
                throw new RuntimeException("System.getProperty(\"os.name\")无法获取操作系统类型");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取本机IP
     * @return
     */
    public static String getLocalHostIP() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String ip = addr.getHostAddress().toString(); //获取本机ip
        return ip;
    }

    /**
     * 获取本机名称
     * @return
     */
    public static String getLocalHostName() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String hostName=addr.getHostName().toString(); //获取本机计算机名称
        return hostName;
    }
}
